<?php
//require_once 'dr-app-config.php';
//echo '<pre>';

require_once 'dr-db-options.php';
require_once 'dr-db-histories.php';
$reputation_options = array(
	'question_send',
	'answer_send',
	'comment_send',
	'upvote_send',
	'downvote_send',
	'upvote_get',
	'downvote_get',
	'mark_question',
	'mark_people',
	'mark_tag',
	'marks_get'
);

$default_reputation_settings = array(
	'question_send' => 1,
	'answer_send' => 1,
	'comment_send' => 0,
	'upvote_send' => 1,
	'downvote_send' => -2,
	'upvote_get' => 5,
	'downvote_get' => -2,
	'mark_question' => 0,
	'mark_people' => 0,
	'mark_tag' => 0,
	'marks_get' => 0
);

/**
 * XXX 获得系统设定的用户的某个动作的积分值
 *
 * @param string|array $options
 * @param boolean $array
 */
function dr_db_get_reputation_settings()
{
	global $db, $reputation_options, $default_reputation_settings;
	$reputation_settings = array();
	foreach ($reputation_options as $option) {
		$reputation_settings[$option] = dr_db_get_option($option, $default_reputation_settings[$option]);
	}
	return $reputation_settings;
}

function dr_db_update_all_reputation_settings($reputation_settings)
{
	foreach ($reputation_settings as $option => $value) {
		dr_db_update_option($option, $value);
	}
	dr_db_update_all_user_reputations_after_setting();
	return true;
}

function dr_db_update_all_user_reputations_after_setting()
{
	global $db, $reputation_options;
	$records = dr_db_get_all_user_record_histories();
	var_dump($records);
	$reputation_settings = dr_db_get_reputation_settings();
	var_dump($reputation_settings);
	foreach ($records as $record) {
		$points = 0;
		foreach ($reputation_options as $option) {
			$points += $record[$option] * $reputation_settings[$option];
		}
		dr_db_update_user_reputation_after_setting($record['user_id'], $points);
	}
}

//dr_db_update_all_user_reputations_after_setting();

function dr_db_update_user_reputation_after_setting($user_id, $points)
{
	global $db;
	$sql = 'UPDATE ^users SET points = $ WHERE user_id = $';
	return dr_db_query_sub($db, $sql, $points, $user_id);
}

/**
 * XXX 需要优化获得配置信息的方法，目前的方法访问数据库的次数过多
 *
 * @param unknown_type $user_id
 * @param unknown_type $rep_type
 */
function dr_db_update_user_reputation($user_id, $rep_type)
{
	global $db;

	$rep_settings = dr_db_get_reputation_settings();

	if ($rep_settings != 0) {
		return dr_db_query_sub($db, 'UPDATE ^users SET points = points + $ WHERE user_id = $', $rep_settings[$rep_type], $user_id);
	}
}